﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using OAclient.Models;
using CommonLibrary.Common;
using ServiceApplication.Service.Basic;
using ServiceApplication.Dao.Basic;
using System.Web.UI;
using OAclient.Common;
using System.Text;
using OAclient.Filters;
using CommonLibrary.DataModel.Basic;
using ValueHelper.FileHelper.FileBase;
using System.Configuration;
using System.Data;
using System.Web.Configuration;
using System.Xml;
using ValueHelper.FileHelper;

namespace OAclient.Controllers
{
    //[VaildateLogin]
    [ExceptionFilter]
    [LoggerFilter]
    [OutputCache(Location = OutputCacheLocation.None)]
    public class WebStoreController : Controller
    {
        //
        // GET: /WebStore/

        BasicService bs = new BasicService();
        Encoding utf8 = Encoding.UTF8;

        String baseUrl = Path.Combine(ComVariable.StoreUrl, "webstore");

        //
        public ActionResult WebStore(UserModel user)
        {
            ViewData["auth"] = "user";
            if (user.user.user_loginid == "admin")
                ViewData["auth"] = "manager";

            ViewData["userId"] = user.user.user_id.ToString();
            ViewData["rootPath"] = baseUrl;


            return View();
        }

        ///  获得网盘列表
        public ActionResult GetFolders(String folderPID, UserModel user)
        {
            if (String.IsNullOrEmpty(folderPID))
                folderPID = "0";

            var folderList = bs.StoreGetFolders(folderPID, user.user.user_id.ToString());

            var json = new
            {
                folders = (from folder in folderList.Folders
                           select new
                           {
                               id = folder.FolderID,
                               name = folder.FolderName,
                               pid = folder.FolderPID,
                               updateTime = folder.UpdateTime.Substring(0, folder.UpdateTime.Length - 8),
                               userID = folder.UserID,
                           }),
                files = (from file in folderList.Files
                         select new
                         {
                             name = file.file_name,
                             filesize = file.file_size + "KB",
                             updateTime = file.file_utime.Substring(0, file.file_utime.Length - 8),
                             replacename = file.file_replacename + file.file_ext,
                             id = file.file_id,
                             share = file.file_share,
                             ext = file.file_ext
                         })
            };

            return Json(json, JsonRequestBehavior.AllowGet);
        }

        // 获取搜索结果
        public ActionResult GetFolders4Search(String keyword, UserModel user)
        {
            if (String.IsNullOrEmpty(keyword))
                keyword = string.Empty;
            //该用户所有的文件与文件夹
            //var allfolderDt = bs.FolderQueryAllByUserId(user.user.user_id);
            var folderlist = bs.FolderQuery4Fuzzy(keyword, user.user.user_id.ToString());
            var fileList = bs.FileQuery4Fuzzy(keyword, user.user.user_id.ToString());

            var data = new
            {
                folders = (from folder in folderlist.ToArray()
                           select new
                           {
                               id = folder.FolderID,
                               name = folder.FolderName,
                               pid = folder.FolderPID,
                               updateTime = folder.UpdateTime.Substring(0, folder.UpdateTime.Length - 8),
                               userID = folder.UserID,
                           }),
                files = (from file in fileList.ToArray()
                         select new
                         {
                             name = file.file_name,
                             filesize = file.file_size + "KB",
                             updateTime = file.file_utime.Substring(0, file.file_utime.Length - 8),
                             replacename = file.file_replacename + file.file_ext,
                             id = file.file_id,
                             share = file.file_share,
                             ext = file.file_ext,
                         })
            };

            return Json(data, JsonRequestBehavior.AllowGet);
        }

        ///  获得分享网盘列表
        public ActionResult GetShareFilders(UserModel user, String folderPID)
        {
            List<ShareFileModel> folderList = new List<ShareFileModel>();
            if (folderPID == "0")
            {
                folderList = bs.StoreGetShareUser(user.user.user_id);
                var json = new
                {
                    folders = (from folder in folderList
                               select new
                               {
                                   id = folder.userID,
                                   name = folder.userName,
                                   pid = "",
                                   updateTime = "",
                                   userID = folder.userID
                               }),
                    //空数据
                    files = (from file in new List<FileEntity>()
                             select new
                             {
                                 name = file.file_name,
                                 filesize = file.file_size + "KB",
                                 updateTime = file.file_utime,
                                 replacename = file.file_replacename + file.file_ext,
                                 id = file.file_id,
                                 share = file.file_share,
                                 ext = file.file_ext
                             })
                };

                return Json(json, JsonRequestBehavior.AllowGet);
            }
            else
            {
                folderList = bs.StoreGetShareFiles(folderPID);

                var json = new
                {
                    //空数据
                    folders = (from folder in new List<ShareFileModel>()
                               select new
                               {
                                   id = folder.userID,
                                   name = folder.userName,
                                   pid = "",
                                   updateTime = "",
                                   userID = folder.userID
                               }),
                    files = (from files in folderList
                             from file in files.files
                             where file.file_share.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Contains(user.user.user_id.ToString())
                             select new
                             {
                                 name = file.file_name,
                                 filesize = file.file_size + "KB",
                                 updateTime = file.file_utime,
                                 replacename = file.file_replacename + file.file_ext,
                                 id = file.file_id,
                                 share = file.file_share,
                                 ext = file.file_ext
                             })
                };

                return Json(json, JsonRequestBehavior.AllowGet);

            }

        }

        ///  获得所有用户网盘
        public ActionResult GetUserFolders(String folderPID)
        {
            if (folderPID == "0")
            {
                var folderList = bs.StoreGetAllFiledUser();
                var json = new
                {
                    folders = (from folder in folderList
                               select new
                               {
                                   id = folder.userID,
                                   name = folder.userName,
                                   pid = "",
                                   updateTime = "",
                                   userID = folder.userID
                               }),
                    files = (from file in new List<FileEntity>()
                             select new
                             {
                                 name = file.file_name,
                                 filesize = file.file_size + "KB",
                                 updateTime = file.file_utime,
                                 replacename = file.file_replacename + file.file_ext,
                                 id = file.file_id,
                                 share = file.file_share,
                                 ext = file.file_ext
                             })
                };

                return Json(json, JsonRequestBehavior.AllowGet);
            }
            else
            {
                var folderList = bs.StoreGetAllUserFiles(folderPID);
                var json = new
                {
                    folders = (from folder in new List<ShareFileModel>()
                               select new
                               {
                                   id = folder.userID,
                                   name = folder.userName,
                                   pid = "",
                                   updateTime = "",
                                   userID = folder.userID
                               }),
                    files = (from files in folderList
                             from file in files.files
                             select new
                             {
                                 name = file.file_name,
                                 filesize = file.file_size + "KB",
                                 updateTime = file.file_utime,
                                 replacename = file.file_replacename + file.file_ext,
                                 id = file.file_id,
                                 share = file.file_share,
                                 ext = file.file_ext
                             })
                };

                return Json(json, JsonRequestBehavior.AllowGet);
            }
        }

        ///  新建文件夹
        public ActionResult CreateFolder(String folderName, String folderPID, UserModel user)
        {
            var ctime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            var result = bs.StoreAddFolder(folderName, ctime, user.user.user_id.ToString(), folderPID);
            if (result)
                return Content("Success");
            else
                return Content("Failed");
        }

        ///  删除文件夹
        /// <param name="force">是否强制删除</param>
        public ActionResult DelelteFolder(String folderIDs, String force)
        {
            var folderIDSet = CommonMethod.splitString(folderIDs, ';');
            var result = true;

            for (int index = 0; index < folderIDSet.Length; index++)
            {
                result = bs.StoreDeleteFolder(folderIDSet[index], baseUrl, Boolean.Parse(force));
                if (!result)
                    break;
            }

            if (result)
                return Content("Success");
            else
                return Content("Failed");
        }

        ///  修改文件夹
        public ActionResult ChangeFolder(String folderID, String folderPID, String folderName, UserModel user)
        {
            var time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            var result = bs.StoreChangeFolder(folderID, folderName, time, folderPID, user.user.user_id.ToString());
            if (result)
                return Content("Success");
            else
                return Content("Failed");
        }

        ///  移动文件夹
        public ActionResult MoveFolder(String folderID, String folderPID, UserModel user)
        {
            Boolean result = true;
            String[] ids = folderID.Split(new Char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var id in ids)
            {
                if (id == folderPID)
                {
                    result = false;
                    continue;
                }
                if (result)
                    result = bs.StoreMoveFolder(id, folderPID, user.user.user_id.ToString());

            }
            if (result)
                return Content("Success");
            else
                return Content("Failed");
        }

        //上传文件 旧2013.01.27
        //public ActionResult UploadFile()
        //{
        //    try
        //    {
        //        string replacename = DateUtil.getStringTimeBySecond() + new Random().Next(1, 10);

        //        //相对路径 例如： person\\1\\a.jpg
        //        //string file_path = replacename + fileExtend;
        //        string file_path = replacename;
        //        if (!Directory.Exists(baseUrl))
        //            Directory.CreateDirectory(baseUrl);
        //        String saveFileName = Path.Combine(baseUrl, file_path);
        //        //var size = ControllerContext.HttpContext.Request.ContentLength;
        //        IServiceProvider provider = (IServiceProvider)ControllerContext.HttpContext;
        //        HttpWorkerRequest httpWorkerRequest = (HttpWorkerRequest)(provider.GetService(typeof(HttpWorkerRequest)));
        //        var size = httpWorkerRequest.GetTotalEntityBodyLength() / 1024 / 1024;
        //        if (size > 50)
        //        {
        //            return Content("上传文件应小于50M");
        //        }
        //        WebHelper.ValueUpload.ValueUpload upload = new WebHelper.ValueUpload.ValueUpload(ControllerContext.HttpContext);
        //        WebHelper.ValueUpload.Infrastructure.UploadInfo uploadInfo = upload.SaveAs("fileupload", saveFileName);
        //        if (uploadInfo.Success)
        //        {
        //            var fileExtend = Path.GetExtension(uploadInfo.FileName).ToLower();
        //            FileEntity fe = new FileEntity()
        //            {
        //                file_id = -1,
        //                file_name = uploadInfo.FileName,
        //                file_replacename = replacename,
        //                file_ctime = DateUtil.getStandardTimeBySecond(),
        //                file_descn = string.Empty,
        //                file_ext = fileExtend,
        //                file_mime = FileHelper.GetFileMIME(fileExtend),
        //                file_path = file_path,
        //                file_size = (uploadInfo.FileLength / 1024).ToString("f2"),
        //                user_id = Int32.Parse(uploadInfo.Form["ownerID"]),
        //                file_catalog = "",
        //                file_share = "",
        //                file_utime = DateUtil.getStandardTimeBySecond(),
        //                folderID = uploadInfo.Form["folderID"]
        //            };

        //            bs.StoreAddFile(fe);
        //            return Content("Success");
        //        }
        //        return Content("Failed");
        //    }
        //    catch
        //    {
        //        return Content("Failed");

        //    }
        //    //foreach (String upload in Request.Files)
        //    //{
        //    //    if (Request.Files[upload] != null)
        //    //    {
        //    //        var fileFullName = Request.Files[upload].FileName;
        //    //        if (string.IsNullOrEmpty(fileFullName))
        //    //            continue;

        //    //        var fileNames = Path.GetFileName(fileFullName);

        //    //        var fileExtend = Path.GetExtension(fileNames).ToLower();

        //    //        string replacename = DateUtil.getStringTimeBySecond() + new Random().Next(1, 10);

        //    //        //相对路径 例如： person\\1\\a.jpg
        //    //        string file_path = replacename + fileExtend;
        //    //        FileEntity fe = new FileEntity()
        //    //        {
        //    //            file_id = -1,
        //    //            file_name = fileNames,
        //    //            file_replacename = replacename,
        //    //            file_ctime = DateUtil.getStandardTimeBySecond(),
        //    //            file_descn = string.Empty,
        //    //            file_ext = fileExtend,
        //    //            file_mime = FileHelper.GetFileMIME(fileExtend),
        //    //            file_path = file_path,
        //    //            file_size = (Request.Files[upload].ContentLength / 1024).ToString("f2"),
        //    //            user_id = user.user.user_id,
        //    //            file_catalog = "",
        //    //            file_share = "false",
        //    //            file_utime = DateUtil.getStandardTimeBySecond(),
        //    //            folderID = folderID
        //    //        };
        //    //        bs.StoreAddFile(fe);
        //    //        if (!Directory.Exists(baseUrl))
        //    //            Directory.CreateDirectory(baseUrl);
        //    //        Request.Files[upload].SaveAs(Path.Combine(baseUrl, file_path));
        //    //        return Content("Success");
        //    //    }
        //    //}

        //    //return Content("Failed");
        //}

        /// 上传文件 新2013.01.27
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult UploadFile(HttpPostedFileBase fileData, string user_id, string folder_id)
        {
            if (fileData != null)
            {
                try
                {
                    string replacename = fileData.InputStream.GetFileHashName();
                    //string replacename = DateUtil.getStringTimeBySecond() + new Random().Next(1, 10);
                    string file_path = replacename;
                    String savePathFullName = Path.Combine(baseUrl, replacename);// 保存文件名称
                    // 文件上传后的保存路径
                    if (!Directory.Exists(baseUrl))
                    {
                        Directory.CreateDirectory(baseUrl);
                    }
                    string fileName = Path.GetFileName(fileData.FileName);// 原始文件名称
                    string fileExtend = Path.GetExtension(fileName); // 文件扩展名

                    fileData.SaveAs(savePathFullName + fileExtend);
                    FileEntity fe = new FileEntity()
                    {
                        file_id = -1,
                        file_name = fileName,
                        file_replacename = replacename,
                        file_ctime = DateUtil.getStandardTimeBySecond(),
                        file_descn = string.Empty,
                        file_ext = fileExtend,
                        file_mime = OAclient.Common.FileHelper.GetFileMIME(fileExtend),
                        file_path = file_path,
                        file_size = (fileData.ContentLength / 1024).ToString("f2"),
                        user_id = Int32.Parse(user_id),
                        file_catalog = "",
                        file_share = "",
                        file_utime = DateUtil.getStandardTimeBySecond(),
                        folderID = folder_id
                    };

                    bs.StoreAddFile(fe);


                    return Json(new { Success = true, FileName = fileName, SaveName = replacename });
                }
                catch (Exception ex)
                {
                    return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {

                return Json(new { Success = false, Message = "请选择要上传的文件！" }, JsonRequestBehavior.AllowGet);
            }
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult UploadFile()
        {
            return View();
        }

        ///  删除文件
        public ActionResult DeleteFile(String fileIDs)
        {
            var fileIDsSet = CommonMethod.splitString(fileIDs, ';');
            for (int index = 0; index < fileIDsSet.Length; index++)
            {
                bs.StoreDelelteFile(fileIDsSet[index], baseUrl);
            }
            return Content("Success");
        }

        ///  下载文件
        public ActionResult DownloadFile(String fileName)
        {
            string mime = OAclient.Common.FileHelper.GetFileMIME(Path.GetExtension(fileName));
            String filePath = Path.Combine(baseUrl, fileName);

            if (!System.IO.File.Exists(filePath))
            {
                Response.Write("<script language='javascript'>showmsg(); function showmsg(){alert('文件不存在,下载失败');}</script>");
                return View("Error404");
            }

            return File(new FileStream(filePath, FileMode.Open, FileAccess.Read), mime, fileName);
        }

        ///  分享文件
        public ActionResult ShareFiles(String fileIDs, String shareIDs)
        {
            var fileIDSet = CommonMethod.splitString(fileIDs, ';');
            foreach (var id in fileIDSet)
            {
                bs.StoreShareFile(id, shareIDs);
            }
            return Content("Success");
        }

        ///  分享文件夹下所有文件
        public ActionResult ShareFolders(String folderIDs, String shareIDs)
        {
            var folderIDSet = folderIDs.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var id in folderIDSet)
            {
                var dt_childfolders = bs.StoreGetFolders(id);
                if (dt_childfolders != null && dt_childfolders.Rows.Count > 0)
                {
                    for (int i = 0; i < dt_childfolders.Rows.Count; i++)
                    {
                        ShareFolders(dt_childfolders.Rows[i]["folder_id"].ToString(), shareIDs);
                    }
                }
                bs.StoreShareFileByFolderID(id, shareIDs);
            }
            return Content("Success");
        }

        ///  取消分享
        public ActionResult UnshareFile(String fileID)
        {
            bs.StroeUnshareFile(fileID);
            return Content("Success");
        }

        ///  获得文件树
        public ActionResult GetStoreTree(UserModel user)
        {
            var result = bs.StoreGetStoreJsonString(user.user.user_id.ToString());
            return Content(result);
        }

        ///  移动文件
        public ActionResult MoveFile(String fileID, String folderID)
        {
            String[] ids = fileID.Split(new Char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var id in ids)
            {
                bs.StoreMoveFile(id, folderID);
            }
            return Content("Success");
        }

        ///  复制分享文件
        public ActionResult CopyShareFile(String fileID, String folderID, UserModel user)
        {
            var file = bs.StoreGetFile(fileID);
            var fileName = Path.Combine(baseUrl, file.file_replacename + file.file_ext);
            if (!System.IO.File.Exists(fileName))
                return Content("Failed");

            string replacename = DateUtil.getStringTimeBySecond() + new Random().Next(1, 10);
            string file_path = replacename + file.file_ext;
            FileEntity fe = new FileEntity()
            {
                file_id = -1,
                file_name = file.file_name,
                file_replacename = replacename,
                file_ctime = DateUtil.getStandardTimeBySecond(),
                file_descn = string.Empty,
                file_ext = file.file_ext,
                file_mime = OAclient.Common.FileHelper.GetFileMIME(file.file_ext),
                file_path = file_path,
                file_size = file.file_size,
                user_id = user.user.user_id,
                file_catalog = "",
                file_share = "",
                file_utime = DateUtil.getStandardTimeBySecond(),
                folderID = folderID
            };
            bs.StoreAddFile(fe);
            System.IO.File.Copy(Path.Combine(baseUrl, file.file_replacename + file.file_ext),
                Path.Combine(baseUrl, fe.file_replacename + fe.file_ext));

            return Content("Success");
        }

        ///  文件夹重名名
        public ActionResult RenameFolder(String folderID, String folderPID, String rename, UserModel user)
        {
            var result = bs.StoreRenameFolder(folderID, folderPID, rename, user.user.user_id.ToString());
            if (result)
                return Content("Success");
            else
                return Content("Failed");
        }

        ///  文件重命名
        public ActionResult RenameFile(String fileID, String rename)
        {
            bs.StoreRenameFile(fileID, rename);
            return Content("Success");
        }

        ///  读取文件
        public ActionResult ReadFile(String fileName)
        {
            var filePath = Path.Combine(baseUrl, fileName);
            if (!System.IO.File.Exists(filePath))
                return Content("Failed");

            var extension = System.IO.Path.GetExtension(fileName).ToLower();
            var result = String.Empty;

            if (extension == ".doc")
            {
                var wordFile = FileManager.GetWordHelper();
                wordFile.SetFileName(fileName);
                result = wordFile.ReadText();
            }
            else
            {
                var txtFile = FileManager.GetTextHelper();
                txtFile.SetFileName(fileName);
                result = txtFile.ReadText();
            }
            result = result.Replace("\r\n", "<br />");
            return Content(result);

            //var ext = Path.GetExtension(fileName);
            //if (ext == ".txt")
            //{
            //    StreamReader streamReader = new StreamReader(filePath, Encoding.Default);
            //    try
            //    {
            //        String words = streamReader.ReadToEnd();
            //        streamReader.Close();
            //        words = words.Replace("\r\n", "<br />");
            //        return Content(words);
            //    }
            //    catch
            //    {
            //        return Content("Failed");
            //    }
            //}
            ////else if (ext == ".doc")
            ////{
            ////    var words = ComHelper.ReadWord(filePath);
            ////    words = words.Replace("\r\n", "<br />");
            ////    return Content(words);
            ////}
            //return Content("Failed");
        }

        /// 网盘根路径设置
        public ActionResult WebStoreConfig()
        {
            return PartialView();
        }

        // /webstore-2
        public ActionResult DoChangeWebStoreBasePath(string new_path)
        {

            if (!Directory.Exists(new_path))
            {
                Directory.CreateDirectory(new_path);
            }
            try
            {
                DirectoryInfo dirinfo = new DirectoryInfo(ComVariable.StoreUrl);
                if (dirinfo.Exists)
                {
                    CopyDirectoryAndFiles(new_path, dirinfo);

                    string cinfigfilename = Server.MapPath("Web.config");
                    FileInfo fi = new FileInfo(cinfigfilename);
                    XmlDocument document = new XmlDocument();
                    document.Load(fi.FullName);
                    ((XmlElement)document.SelectSingleNode(@"/configuration/appSettings/add[@key='WebStorePath']")).SetAttribute("value", new_path);
                    document.Save(cinfigfilename);
                    return Json(new ResTag(true), JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(new ResTag(false), JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception e)
            {
                return Json(new ResTag(false), JsonRequestBehavior.AllowGet);
            }


        }

        private void CopyDirectoryAndFiles(string des, DirectoryInfo srcDir)
        {
            if (!des.EndsWith("\\"))
            {
                des += "\\";
            }
            string desPath = des + srcDir.Name + "\\";
            if (!Directory.Exists(desPath))
            { Directory.CreateDirectory(desPath); }
            foreach (FileInfo file in srcDir.GetFiles())
            {
                file.CopyTo(desPath + file.Name, true);
            }
            foreach (DirectoryInfo dirinfo in srcDir.GetDirectories())
            {
                CopyDirectoryAndFiles(desPath, dirinfo);
            }
        }

        #region 第一版本代码
        //private void AddFolder(String userID)
        //{


        //    foreach (var name in baseFolders)
        //    {
        //        var baseUrl = Server.MapPath("~");
        //        var dirPath = Path.Combine(baseUrl, "webstore\\Person\\" + userID);
        //        dirPath = Path.Combine(dirPath, name);
        //        if (!Directory.Exists(dirPath))
        //            Directory.CreateDirectory(dirPath);
        //    }
        //}

        //public ActionResult AddFolder(String path, String name, UserModel user)
        //{
        //    var baseUrl = Server.MapPath("~");
        //    var dirPath = Path.Combine(baseUrl, path);
        //    dirPath = Path.Combine(dirPath, user.user.user_id.ToString());
        //    dirPath = Path.Combine(dirPath, name);

        //    if (!Directory.Exists(dirPath))
        //        Directory.CreateDirectory(dirPath);
        //    else
        //        return Content("folderExist");
        //    return Content("Success");
        //}

        ////rar; zip; doc; xls; bmp; png; jpeg; gif; txt;
        //public ActionResult fileFromDisk(String path, String fileName, UserModel user)
        //{
        //    //var filePath = combinePath(path, landType, user);
        //    //filePath = Path.Combine(filePath, fileName);
        //    var filePath = Server.MapPath("~");
        //    filePath = Path.Combine(filePath, path);
        //    filePath = Path.Combine(filePath, fileName);


        //    FileInfo f = new FileInfo(filePath);
        //    string mime = FileHelper.GetFileMIME(f.Extension);

        //    //filePath = Request.MapPath("/UploadFiles/") + filePath.Replace("/", "\\");
        //    //bool success = FileHelper.ResponseFile(Request, Response, fileName, filePath, 1024000);
        //    //if (success)
        //    //    return JavaScript("alert('下载成功');");
        //    //else
        //    //    return JavaScript("alert('下载失败');");

        //    //2012-08-28 mlh ：360中文文件名下载出问题，注释
        //    //path = HttpUtility.UrlDecode(path, utf8).ToLower();

        //    //string ext = Path.GetExtension(fileName);

        //    if (!System.IO.File.Exists(filePath))
        //    {
        //        Response.Write("<script language='javascript'>showmsg(); function showmsg(){alert('文件不存在,下载失败');}</script>");
        //        return View("Error404");
        //    }

        //    return File(new FileStream(filePath, FileMode.Open, FileAccess.Read), mime, fileName);
        //}


        //public ActionResult ShareFolder(String files, UserModel user)
        //{
        //    //if (isShareLand(path))
        //    //    return Content("shareland");
        //    var baseUrl = Server.MapPath("~");
        //    var dirPath = Path.Combine(baseUrl, "webstore\\Share");
        //    dirPath = Path.Combine(dirPath, user.user.user_id.ToString());
        //    if (!Directory.Exists(dirPath))
        //        Directory.CreateDirectory(dirPath);
        //    var file_ids = CommonMethod.splitString(files);
        //    try
        //    {
        //        foreach (var item in file_ids)
        //        {
        //            //var fileName = Path.Combine(dirPath, item);
        //            //var sharefileName = Path.Combine(baseUrl, "webstore");
        //            //sharefileName = Path.Combine(sharefileName, "Share");
        //            //sharefileName = Path.Combine(sharefileName, user.user.user_id.ToString());
        //            //sharefileName = Path.Combine(sharefileName, item);
        //            //var file = new FileInfo(fileName);
        //            //file.CopyTo(sharefileName, false);
        //            bs.FileShare(item, "true");
        //        }
        //        return Content("Success");
        //    }
        //    catch (Exception e)
        //    {
        //        return Content("fileExsit");
        //    }
        //}

        //public ActionResult CancelShare(String file_id, UserModel user)
        //{
        //    try
        //    {
        //        bs.FileShare(file_id, "false");
        //        return Content("Success");
        //    }
        //    catch (Exception e)
        //    {
        //        return Content("Fail");
        //    }
        //}

        //private Boolean validateExtend(String extend)
        //{
        //    var extends = ".rar;.zip;.doc;.xls;.bmp;.png;.jpeg;.gif;.txt;.jpg;";
        //    if (extends.Split(';').Contains(extend))
        //        return true;
        //    else
        //        return false;
        //}

        //private Boolean fileExist(String dirPath, String fileFullName)
        //{
        //    //var fileName = Path.GetFileNameWithoutExtension(fileFullName);
        //    var file = Directory.GetFiles(dirPath, fileFullName);
        //    if (file.Length > 0)
        //        return true;
        //    else
        //        return false;
        //}

        //private String getUserName(String id)
        //{
        //    var user = bs.QueryUser(Int32.Parse(id));
        //    var name = "";
        //    if (user != null)
        //        name = user.user_name;
        //    return name;
        //}

        //public ActionResult GetStore(String url, Int32? pageIndex, String searchtext)
        //{
        //    pageIndex = pageIndex ?? 1;
        //    var dirsInfo = new dirctoryList();
        //    if (isManageLand(url))
        //        dirsInfo = getdirsInfoForMng(url, pageIndex.Value);
        //    else
        //    {
        //        dirsInfo = getdirsInfo(url, pageIndex.Value);
        //    }

        //    var user_id = url.Substring(url.LastIndexOf("\\") + 1);
        //    var jsonData = new
        //    {
        //        folders = (from dir in dirsInfo.DirsInfo
        //                   select new
        //                   {
        //                       name = dir.FolderName,
        //                       displayname = dir.DisplayName,
        //                       files = (from file in GetFiles(url, dir.FolderName, user_id)
        //                                select new
        //                                {
        //                                    dirctoryname = isShareLand(url) ? file.file_catalog : dir.FolderName,
        //                                    name = file.file_name,
        //                                    filesize = file.file_size,
        //                                    createtime = file.file_ctime,
        //                                    replacename = file.file_replacename + file.file_ext,
        //                                    id = file.file_id,
        //                                    share = file.file_share
        //                                }).ToArray(),
        //                       //totalpage = dir.PageInfo.TotalPages,
        //                       //currentpage = "1"
        //                   }).ToArray(),
        //        //totalpage = dirsInfo.PageInfo.TotalPages,
        //        //currentpage = pageIndex.Value
        //    };

        //    return Json(jsonData, JsonRequestBehavior.AllowGet);
        //}

        ///// <summary>
        /////  根据类型获取文件
        ///// </summary>
        ///// <param name="url"></param>
        ///// <param name="folderName"></param>
        ///// <param name="user_id"></param>
        ///// <returns></returns>
        //private List<FileEntity> GetFiles(String url, String folderName, String user_id)
        //{
        //    if (isShareLand(url))
        //        return GetShareFiles(folderName);
        //    if (isManageLand(url))
        //        return GetFiles(folderName);

        //    return GetFiles(folderName, user_id);
        //}

        ///// <summary>
        /////  获取用户所有文件
        ///// </summary>
        ///// <param name="user_id"></param>
        ///// <returns></returns>
        //private List<FileEntity> GetFiles(String user_id)
        //{
        //    var files = bs.FilesQuery(user_id);
        //    return files;
        //}

        ///// <summary>
        /////  获取用户共享文件
        ///// </summary>
        ///// <param name="user_id"></param>
        ///// <returns></returns>
        //private List<FileEntity> GetShareFiles(String user_id)
        //{
        //    var files = bs.FilesQuery(user_id);
        //    var result = (from file in files
        //                  where file.file_share == "true"
        //                  select file).ToList();
        //    return result;
        //}

        ///// <summary>
        /////  获取用户分类文件
        ///// </summary>
        ///// <param name="file_catalog"></param>
        ///// <param name="userId"></param>
        ///// <returns></returns>
        //private List<FileEntity> GetFiles(String file_catalog, string userId)
        //{
        //    var files = bs.FilesQuery(file_catalog, userId);

        //    return files;
        //}

        //public ActionResult SearchFiles(String searchtext, UserModel user)
        //{
        //    var files = bs.FilesQuery(user.user.user_id.ToString());
        //    var result = files;
        //    if (!String.IsNullOrEmpty(searchtext))
        //    {
        //        result = (from file in files
        //                  where file.file_name.Contains(searchtext)
        //                  select file).ToList();
        //    }

        //    var json = new
        //    {
        //        folders = new Object[]
        //        {
        //            new {
        //            name = "搜索结果",
        //            displayname = "搜索结果",
        //            files = (from file in result
        //                     select new
        //                     {
        //                         dirctoryname = file.file_catalog,
        //                         name = file.file_name,
        //                         filesize = file.file_size,
        //                         createtime = file.file_ctime,
        //                         replacename = file.file_replacename + file.file_ext,
        //                         id = file.file_id,
        //                         share = file.file_share
        //                     }).ToArray()
        //            }
        //        }
        //    };

        //    return Json(json, JsonRequestBehavior.AllowGet);
        //}

        ////public void MoveFile(String replacename, String catalog)
        ////{
        ////    var file = bs.FileQuery(replacename);
        ////    if (file.file_catalog == catalog)
        ////        return;
        ////    var baseUrl = Server.MapPath("~");
        ////    var dirPath = Path.Combine(baseUrl, "webstore\\Person\\" + file.user_id);
        ////    var origFileName = Path.Combine(dirPath, file.file_catalog + "\\" + file.file_replacename + file.file_ext);
        ////    var newFileName = Path.Combine(dirPath, catalog + "\\" + file.file_replacename + file.file_ext);

        ////    if (System.IO.File.Exists(origFileName))
        ////    {
        ////        System.IO.File.Move(origFileName, newFileName);
        ////        bs.FileMove(file.file_id.ToString(), catalog);
        ////    }
        ////}

        ////public ActionResult GetFile(String url, Boolean isMng, Int32? pageIndex)
        ////{
        ////    pageIndex = pageIndex ?? 1;
        ////    var dirInfo = new dirctoryInfo();
        ////    var baseUrl = Server.MapPath("~");
        ////    var path = Path.Combine(baseUrl, url);
        ////    var files = getfilesInfo(path, "");
        ////    var foldername = path.Substring(path.LastIndexOf('\\') + 1);
        ////    var folder = new dirctoryInfo
        ////    {
        ////        FolderName = foldername,
        ////        DisplayName = isMng == true ? getUserName(foldername) : foldername,
        ////        PageInfo = new PagingInfo
        ////        {
        ////            CurrentPage = pageIndex.Value,
        ////            ItemsPerPage = ItemsPerPage - 5,
        ////            TotalItems = files.Count
        ////        },
        ////        Files = files.Skip((pageIndex.Value - 1) * (ItemsPerPage - 5)).Take(ItemsPerPage - 5).ToList()
        ////    };
        ////    var json = new
        ////    {

        ////        name = folder.FolderName,
        ////        displayname = folder.DisplayName,
        ////        files = (from file in folder.Files
        ////                 select new
        ////                 {
        ////                     dirctoryname = file.DirctoryName,
        ////                     name = file.FileName,
        ////                     filesize = file.FileSize,
        ////                     createtime = file.Createtime
        ////                 }).ToArray(),
        ////        totalpage = folder.PageInfo.TotalPages,
        ////        currentpage = "1"
        ////    };

        ////    return Json(json, JsonRequestBehavior.AllowGet);
        ////}

        //public ActionResult DeleteFolder(String path)
        //{
        //    try
        //    {
        //        var baseUrl = Server.MapPath("~");
        //        var dirPath = Path.Combine(baseUrl, path);
        //        Directory.Delete(dirPath, false);
        //        return Content("Success");
        //    }
        //    catch (Exception e)
        //    {
        //        return Content("fileExsit");
        //    }
        //}

        //public ActionResult DeleleFiles(String path, String files)
        //{
        //    var baseUrl = Server.MapPath("~");
        //    var dirPath = Path.Combine(baseUrl, path);
        //    var fileids = CommonMethod.splitString(files);
        //    try
        //    {
        //        foreach (var item in fileids)
        //        {
        //            var file = bs.FileQuery(Int32.Parse(item));
        //            if (file != null)
        //            {
        //                var fileName = Path.Combine(dirPath, file.file_replacename + file.file_ext);
        //                System.IO.File.Delete(fileName);
        //                bs.FileDelete(Int32.Parse(item));
        //            }
        //        }
        //        return Content("Success");
        //    }
        //    catch (Exception e)
        //    {
        //        return Content("Fail");
        //    }
        //}

        //public ActionResult GetShareFile(String replacename, String catalogname, UserModel user)
        //{
        //    var file = bs.FileQuery(replacename);
        //    if (file != null)
        //    {
        //        try
        //        {
        //            var rpname = DateUtil.getStringTimeBySecond() + new Random().Next(1, 10);

        //            //相对路径 例如： person\\1\\a.jpg
        //            string file_path = rpname + file.file_ext;
        //            FileEntity fe = new FileEntity()
        //            {
        //                file_id = -1,
        //                file_name = file.file_name,
        //                file_replacename = rpname,
        //                file_ctime = DateUtil.getStandardTimeBySecond(),
        //                file_descn = string.Empty,
        //                file_ext = file.file_ext,
        //                file_mime = FileHelper.GetFileMIME(file.file_ext),
        //                file_path = file_path,
        //                file_size = file.file_size,
        //                user_id = user.user.user_id,
        //                file_catalog = catalogname,
        //                file_share = "false"
        //            };

        //            var baseUrl = Server.MapPath("~");
        //            var dirPath = Path.Combine(baseUrl, "webstore\\Person");
        //            var origfileName = Path.Combine(dirPath, file.user_id.ToString() + "\\" + file.file_catalog + "\\" + file.file_replacename + file.file_ext);
        //            var newfileName = Path.Combine(dirPath, user.user.user_id.ToString() + "\\" + catalogname + "\\" + rpname + file.file_ext);

        //            System.IO.File.Copy(origfileName, newfileName);

        //            bs.FileAdd(fe);

        //            return Content("Success");
        //        }
        //        catch
        //        {
        //            return Content("Fail");
        //        }
        //    }
        //    return Content("Fail");
        //}

        //private Boolean isShareLand(String url)
        //{
        //    return "webstore\\Share".Equals(url, StringComparison.OrdinalIgnoreCase);
        //}

        //private Boolean isManageLand(String url)
        //{
        //    return "webstore\\Person".Equals(url, StringComparison.OrdinalIgnoreCase);
        //}

        //private dirctoryList getdirsInfo(String url, Int32 pageIndex)
        //{
        //    var sharePath = isShareLand(url);
        //    var baseUrl = Server.MapPath("~");
        //    var path = Path.Combine(baseUrl, url);
        //    if (!Directory.Exists(path))
        //        Directory.CreateDirectory(path);
        //    var dirs = Directory.GetDirectories(path);
        //    dirctoryList dirsInfo = new dirctoryList();
        //    //dirsInfo.PageInfo = new PagingInfo
        //    //{
        //    //    CurrentPage = pageIndex,
        //    //    ItemsPerPage = ItemsPerPage,
        //    //    TotalItems = dirs.Count()
        //    //};
        //    //if (dirs.Count() > 0)
        //    //    dirs = dirs.Skip((pageIndex - 1) * ItemsPerPage).Take(ItemsPerPage).ToArray();


        //    foreach (var dir in dirs)
        //    {
        //        var folder = new DirectoryInfo(dir);
        //        var files = folder.GetFiles();

        //        var dirInfo = new dirctoryInfo
        //        {
        //            FolderName = folder.Name,
        //            DisplayName = sharePath == true ? getUserName(folder.Name) : folder.Name,
        //            //PageInfo = new PagingInfo
        //            //{
        //            //    CurrentPage = 1,
        //            //    ItemsPerPage = ItemsPerPage - 5,
        //            //    TotalItems = files.Count(),
        //            //}
        //        };
        //        //if (files.Count() > 0)
        //        //    files = files.Take(ItemsPerPage - 5).ToArray();

        //        //foreach (var file in files)
        //        //{
        //        //    dirInfo.Files.Add(new fileInfo
        //        //    {
        //        //        DirctoryName = folder.Name,
        //        //        FileName = file.Name,
        //        //        FileSize = file.Length.ToString(),
        //        //        Createtime = file.CreationTime.ToString("yyyy-MM-dd")
        //        //    });
        //        //}
        //        dirsInfo.DirsInfo.Add(dirInfo);
        //    }
        //    return dirsInfo;
        //}

        //private dirctoryList getdirsInfoForMng(String url, Int32 pageIndex)
        //{
        //    var baseUrl = Server.MapPath("~");
        //    var path = Path.Combine(baseUrl, url);
        //    var dirs = Directory.GetDirectories(path);
        //    dirctoryList dirsInfo = new dirctoryList();
        //    //dirsInfo.PageInfo = new PagingInfo
        //    //{
        //    //    CurrentPage = pageIndex,
        //    //    ItemsPerPage = ItemsPerPage,
        //    //    TotalItems = dirs.Count()
        //    //};
        //    //if (dirs.Count() > 0)
        //    //    dirs = dirs.Skip((pageIndex - 1) * ItemsPerPage).Take(ItemsPerPage).ToArray();

        //    foreach (var dir in dirs)
        //    {
        //        var folder = new DirectoryInfo(dir);
        //        if (folder.Name.Equals("Default", StringComparison.OrdinalIgnoreCase))
        //            continue;
        //        var dirInfo = new dirctoryInfo
        //        {
        //            FolderName = folder.Name,
        //            DisplayName = getUserName(folder.Name)
        //        };
        //        dirInfo.Files.AddRange(getfilesInfo(dir, ""));
        //        //dirInfo.PageInfo = new PagingInfo
        //        //{
        //        //    CurrentPage = 1,
        //        //    ItemsPerPage = ItemsPerPage - 5,
        //        //    TotalItems = dirInfo.Files.Count
        //        //};

        //        //dirInfo.Files = dirInfo.Files.Take(ItemsPerPage - 5).ToList();
        //        dirsInfo.DirsInfo.Add(dirInfo);
        //    }
        //    return dirsInfo;
        //}

        //private List<fileInfo> getfilesInfo(String path, String foldername)
        //{
        //    List<fileInfo> filesInfo = new List<fileInfo>();
        //    //var dirs = Directory.GetDirectories(path);

        //    var dirsinst = new DirectoryInfo(path);
        //    var files = dirsinst.GetFiles();
        //    foreach (var file in files)
        //    {
        //        filesInfo.Add(new fileInfo
        //        {
        //            DirctoryName = foldername,
        //            FileName = file.Name,
        //            FileSize = file.Length.ToString(),
        //            Createtime = file.CreationTime.ToString("yyyy-MM-dd")
        //        });
        //    }

        //    var dirs = dirsinst.GetDirectories();
        //    var count = dirs.Length;
        //    if (count > 0)
        //    {
        //        for (int i = 0; i < count; i++)
        //            filesInfo.AddRange(getfilesInfo(dirs[i].FullName, dirs[i].Name));
        //    }
        //    return filesInfo;
        //}

        //private class dirctoryList
        //{
        //    public dirctoryList()
        //    {
        //        dirsInfo = new List<dirctoryInfo>();
        //    }

        //    private List<dirctoryInfo> dirsInfo;
        //    public List<dirctoryInfo> DirsInfo
        //    {
        //        get { return dirsInfo; }
        //        set { dirsInfo = value; }
        //    }

        //    public PagingInfo PageInfo { get; set; }
        //}

        //private class dirctoryInfo
        //{
        //    public dirctoryInfo()
        //    {
        //        files = new List<fileInfo>();
        //    }

        //    public String DisplayName { get; set; }
        //    public String FolderName { get; set; }

        //    public PagingInfo PageInfo { get; set; }

        //    private List<fileInfo> files;
        //    public List<fileInfo> Files { get { return files; } set { files = value; } }
        //}

        //private class fileInfo
        //{
        //    public String FileName { get; set; }
        //    public String OwnerId { get; set; }
        //    public String FileSize { get; set; }
        //    public String Createtime { get; set; }
        //    public String OwnerName { get; set; }
        //    public String DirctoryName { get; set; }
        //}

        #endregion
    }
}
